//
//  StatuesListViewModel.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/13.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit

class StatuesListViewModel: NSObject {

    lazy var statusList: [StatueViewModel] = [StatueViewModel]()
    
    //加载微博数据
    func loadStatus( isPullUp: Bool, callBack: (isSuccess: Bool, message: String)->())  {
        //  上拉加载默认值0
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        if isPullUp {
            //  获取数组里面最后一个微博元素的微博id
            maxId = statusList.last?.statues?.id ?? 0
            //  防止获取重复的数据,我们对其微博id减1
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            //  获取数组里面的第一个微博元素的微博id
            sinceId = statusList.first?.statues?.id ?? 0
        }
        
        var message = "没有加载到最新微博数据"
        NetworkingTools.sharedTools.loadStatues(maxId, sinceId: sinceId) { (response, error) -> () in
            if error != nil{
                
                print(error)
                callBack(isSuccess: false, message: message)
                return
            }
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的json")
                callBack(isSuccess: false , message: message)
                return
            }
            guard let statusDicArray = dic["statuses"] as? [[String: AnyObject]] else {
                print("不是一个正确的字典")
                callBack(isSuccess: false, message: message)
                return
            }
            var tempArr = [StatueViewModel]()
            for statusDic in statusDicArray {
                let status = Statues(dic: statusDic)
                let statusViewModel = StatueViewModel(statues: status)
                
                tempArr.append(statusViewModel)
            }
            //上啦加载  就追加数组元素
            if isPullUp {
                self.statusList.appendContentsOf(tempArr)
            } else {
                //下拉刷新  追加数组元素
                self.statusList.insertContentsOf(tempArr, at: 0)
            }

            if tempArr.count > 0 {
                message = "加载了\(tempArr.count)条微博数据"
            }
            self.statusList.appendContentsOf(tempArr)
            callBack(isSuccess: true, message: message)

            
        }
        
        
        
    }
}
